# coding=utf-8
import pickle
import pprint
import sys


method = sys.argv[1]

if method == 'r':
    category = sys.argv[2]
    title = sys.argv[3]

'''
密码管理器

* 保存密码
* 获取密码

格式：
 * 密码 title
 * {"title": "passwd"}

分类：
 * web
 * 服务器

格式：
 {
 "web":{"jingfeng":"123456", "zhihu":"123456"}
 }
 title | passwd | url

自动生成安全密码 （用户可以输入长度）
'''


def select_db():
    try:
        with open('zpass.pass', 'rb') as f:
            return pickle.load(f)
    except Exception as e:
        return False
    


def insert_db(obj):
    with open('zpass.pass', 'wb') as f:
        pickle.dump(obj, f)


class PassWord(dict):
    
    def __init__(self, category, title, user, passwd):
        '''
        {'title':
                    {
                        user:test, 
                        passwd:123456, 
                        url:jingfeng.com
                    }
        }
        '''
        super().__init__()
        self.title = title
        self.category = category
        self[title] = {'user': user, 'passwd': passwd}


    def passwd_data(self):
        '''
        {'title': 'test', 'user': 'test', 'passwd': '123456', 'url': 'url.com'}
        |
        V
        {
            'web':{'title':
                    {
                        user:test, 
                        passwd:123456, 
                        url:jingfeng.com
                    }
                }
        }
        '''
        pwd_data = select_db() if select_db() else {}
        if not pwd_data:
            pwd_data[self.category] = {}
            pwd_data[self.category][self.title] = self[self.title]
        pwd_data[self.category][self.title] = self[self.title]
        return pwd_data

    def save_passwd(self):
        passwd_data = self.passwd_data()
        pprint.pprint(passwd_data)
        insert_db(passwd_data)
        return True

    @classmethod
    def get_item(cls):
        cls.item = ['title', 'user', 'passwd']
        return cls.item

    @staticmethod
    def get_passwd():
        passwd =  select_db()
        return passwd[category].get(title)


class WebPassWord(PassWord):

    def __init__(self, category, title, user, passwd, url):
        super().__init__(category, title, user, passwd)
        self[title]['url'] = url

    @classmethod
    def get_item(cls):
        super().get_item()
        cls.item.append('url')
        return cls.item


def main():
    if method == 'r':
        print(PassWord.get_passwd())
    elif method == 'w':
        user_choice = input("1 web, 2 server, 0 退出")
        passwd_args = {}
        if user_choice == '1':
            for i in WebPassWord.get_item():
                passwd_args[i] = input(i + ":")
        wpw = WebPassWord(category='web', **passwd_args)
        stat = wpw.save_passwd()
        if stat is False:
            print('保存失败！')
        print('保存成功！')
        if user_choice == '2':
            pass


if __name__ == '__main__':
    main()
